import { computed } from 'vue'
import { useAddChildCommodityType } from '../../param-set/commodity-set'
import { useAddChildNetworkType } from '../../param-set/network-set'
import { useAddChildOrderType } from '../../param-set/order-set'
import { AddChildTypeForm } from './types'

const {
  addChildCommodityTypeForm,
  addChildCommodityTypeLoading,
  addChildCommodityType,
  resetAddChildCommodityTypeForm,
} = useAddChildCommodityType()

const {
  addChildNetworkTypeForm,
  addChildNetworkTypeLoading,
  addChildNetworkType,
  resetAddChildNetworkTypeForm,
} = useAddChildNetworkType()

const {
  addOrderChildTypeForm,
  addOrderChildTypeLoading,
  addOrderChildType,
  resetAddOrderChildTypeForm,
} = useAddChildOrderType()

export default (type: 'commodity' | 'network' | 'order') => {
  const formMap = {
    commodity: addChildCommodityTypeForm,
    network: addChildNetworkTypeForm,
    order: addOrderChildTypeForm,
  }

  const form: AddChildTypeForm = formMap[type]

  const loading = computed(() => {
    return (
      addChildCommodityTypeLoading.value ||
      addChildNetworkTypeLoading.value ||
      addOrderChildTypeLoading.value
    )
  })

  const resetForm = () => {
    switch (type) {
      case 'commodity':
        resetAddChildCommodityTypeForm()
        break
      case 'network':
        resetAddChildNetworkTypeForm()
        break
      case 'order':
        resetAddOrderChildTypeForm()
        break
    }
  }

  const submit = async (orderModuleId?: string) => {
    if (type === 'commodity') {
      return await addChildCommodityType()
    }

    if (type === 'network') {
      return await addChildNetworkType()
    }

    if (type === 'order' && orderModuleId) {
      return await addOrderChildType(orderModuleId)
    }
  }

  return {
    form,
    loading,
    submit,
    resetForm,
  }
}
